package com.itheima.servlet;

import com.itheima.domain.Emp;
import com.itheima.service.EmpService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/emp/*")
public class EmpServlet extends BaseServlet{
    private EmpService service = new EmpService();
    private int page;
    private int total;

    //分页遍历
    protected void listByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        page = 1;
        total = service.getTotal();
        total = total%3==0 ? total/3 : total/3 + 1;
        if(req.getParameter("page")!=null)
        page = Integer.parseInt(req.getParameter("page"));
        List<Emp> list = service.list(page);
        req.setAttribute("page",page);
        req.setAttribute("total",total);
        req.setAttribute("list",list);
        req.getRequestDispatcher("/pages/main.jsp").forward(req, resp);
    }

    //删除数据
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empno = req.getParameter("empno");
        service.delete(empno);
        resp.sendRedirect(req.getContextPath() + "/emp/listByPage");
    }

    //根据编号查找数据
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empno = req.getParameter("empno");
        Emp e = service.findById(empno);
        req.setAttribute("emp",e);
        req.getRequestDispatcher("/pages/operate.jsp").forward(req, resp);//跳转修改页面
    }

    //修改数据
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Emp e = new Emp();
        e.setEmpno(Integer.parseInt(req.getParameter("empno")));
        e.setJob(req.getParameter("job"));
        e.setName(req.getParameter("name"));
        e.setHireDate(req.getParameter("hireDate"));
        e.setSal(Double.parseDouble(req.getParameter("sal")));
        service.update(e);
        resp.sendRedirect(req.getContextPath() + "/emp/listByPage");
    }
}
